#!/usr/bin/env python 
# _*_ coding: utf-8 _*_ 
import base64, time
import httplib, os, urllib, re

external_dev ="eth2"
ddns_domain = "jkzhang.f3322.org"
ddns_user   = "drinkey"
ddns_pass   = "test123"
ddns_server = "members.3322.net"

get_ip_cmd_eth2 = "ip addr show dev " + external_dev +"| awk '/inet/ {print $2}'"
old_ip = ""
cur_ip = ""
# p = re.compile("inet (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s")
p = re.compile("inet ([\d\.])\s")


while True:
    ret = os.popen(get_ip_cmd_eth2)
    cur_ip = ret.readlines()[0]

    if (old_ip != cur_ip):
        old_ip = cur_ip
        print "IP changed, updating DDNS record.."
        params = urllib.urlencode({"system": "dyndns", "hostname": ddns_domain}) 
        auth = base64.b64encode(ddns_user + ':'+ ddns_pass) 
        headers = {"Authorization": "Basic "+ auth} 
        conn = httplib.HTTPConnection(ddns_server) 
        conn.request("GET","/dyndns/update?" + params,"", headers) 
        response = conn.getresponse() 
        #print response.status 
        print response.read().strip()

    time.sleep(1200)

